package ui.fragment.homepagefragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Dailog.CommomDialog;
import Dailog.InputDialog;
import adapter.ExtendListviewAdapter;
import adapter.NoteAdapter;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.NoteCategoryBean;
import bean.People;
import bean.Students;
import student.andlei.com.student.R;
import ui.activity.AddNewNoteActivity;
import ui.activity.MyNoteActivity;
import utils.GsonUtils;
import utils.SPUtils;

/**
 * 笔记
 */
public class NoteFragment extends BaseNetFragment {
    private List<People> pList = new ArrayList<People>();
    private People p1 = new People();
    private People p2 = new People();
    private ExtendListviewAdapter adapter = null;
    private ExpandableListView expandableListView;
    private RecyclerView recyclerView;
    private NoteAdapter noteadapter;
    //    private boolean isWaste;
    // private WastebasketAdapter wastebasketAdapter;
    private LinearLayout layout_search;
    private TextView tv_note_title;
    private EditText ed_search;
    private ImageView img_add;
    private int Searchtype = 0;
    private int p1_Id;//笔记分类id
    private int p2_Id;//垃圾篓分类id

    private List<NoteCategoryBean> lists = new ArrayList();

    public static Fragment getInstance() {
        return new NoteFragment();
    }

    @Override
    public void success(String action, BaseBean baseBean) {
        if (baseBean.code == 200) {
            if (action.equals("note/categoryList")) {
                List<NoteCategoryBean> list = GsonUtils.getInstance(getActivity()).parseNoHeaderJArray(baseBean, NoteCategoryBean.class);
                List<Students> students = new ArrayList<>();
                if (list == null) return;
                boolean havenoteId = false;
                for (NoteCategoryBean bean : list) {
                    Students students1 = new Students();
                    if(bean.category_name.equals("课堂直播笔记")){
                        havenoteId = true;
                        SPUtils.getInstance(context).put("havenoteId",bean.category_id);
                    }
                    students1.setJob(bean.category_name);
                    students1.setId(bean.category_id);
                    students.add(students1);
                }
                if(!havenoteId){
                    Map<String, String> map = new HashMap<>();
                    map.put("name", "课堂直播笔记");
                    post("note/addCategory", map, NoteCategoryBean.class, false);
                }
                p1.setStudents(students);
                adapter.notifyDataSetChanged();
                expandableListView.expandGroup(0);
                if (students.size() <= 0) return;
                tv_note_title.setText(students.get(0).getJob());
                p1_Id = students.get(0).getId();
                Map<String, String> map = new HashMap<>();
                map.put("category_id", p1_Id + "");
                map.put("title", ed_search.getText().toString());
                post("note/noteList", map, NoteCategoryBean.class, false);
            } else if (action.equals("note/basketList")) {
                lists = GsonUtils.getInstance(getActivity()).parseNoHeaderJArray(baseBean, NoteCategoryBean.class);
                for (NoteCategoryBean bean : lists) {
                    bean.isWaste = true;
                }
                noteadapter.setNewData(lists);
//            List<Students> students = new ArrayList<>();
//            if (list == null) return;
//            for (NoteCategoryBean bean : list) {
//                Students students1 = new Students();
//                students1.setJob(bean.title);
//                students1.setId(bean.category_id);
//                students.add(students1);
//            }
//            p2.setStudents(students);
//            adapter.notifyDataSetChanged();
//            expandableListView.expandGroup(1);
            } else if (action.equals("note/noteList")) {
                lists = GsonUtils.getInstance(getActivity()).parseNoHeaderJArray(baseBean, NoteCategoryBean.class);
                noteadapter.setNewData(lists);
            } else if (action.equals("note/addCategory")) {
                post("note/categoryList", new HashMap(), NoteCategoryBean.class, false);
               // toast("新增分类成功");
            } else if (action.equals("note/delCategory")) {
                post("note/categoryList", new HashMap(), NoteCategoryBean.class, false);
                toast("删除分类成功");
            } else if (action.equals("note/clearBasket")) {
                post("note/basketList", new HashMap(), NoteCategoryBean.class, false);
                toast("清空废纸篓成功");
            } else if (action.equals("note/deleteNote")) {
                post("note/basketList", new HashMap(), NoteCategoryBean.class, false);
            } else if (action.equals("note/recoverNote")) {
                post("note/basketList", new HashMap(), NoteCategoryBean.class, false);
            }
        } else {
            if(action.equals("note/addCategory")){return;}
            toast(baseBean.msg);
        }

    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_note;
    }

    @Override
    protected void findViews() {
        expandableListView = getView(R.id.people_lv);
        recyclerView = getView(R.id.rcly_);
        tv_note_title = getView(R.id.tv_note_title);
        layout_search = getView(R.id.layout_search);
        ed_search = getView(R.id.edittext_search);
        img_add = getView(R.id.img_add);
    }

    @Override
    protected void formatViews() {
        img_add.setOnClickListener(this);
        adapter = new ExtendListviewAdapter(this.getActivity(), pList);
        expandableListView.setAdapter(adapter);
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, final int i, long l) {
                Map<String, String> map = new HashMap<>();

                if (i == 0) {
                    layout_search.setVisibility(View.VISIBLE);
                    img_add.setVisibility(View.VISIBLE);
                    if (expandableListView.isGroupExpanded(i)) {
                        expandableListView.collapseGroup(i);
                    } else {
                        //获取分类列表
                        post("note/categoryList", map, NoteCategoryBean.class, false);
                    }

                } else if (i == 1) {
                    layout_search.setVisibility(View.GONE);
                    tv_note_title.setText("废纸篓");
                    img_add.setVisibility(View.GONE);
                    //获取垃圾篓分类列表
                    post("note/basketList", map, NoteCategoryBean.class, false);
                }

                return false;
            }
        });
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, final int i, final int i1, long l) {
                if (i == 0) {
                    layout_search.setVisibility(View.VISIBLE);
                    img_add.setVisibility(View.VISIBLE);
                    Searchtype = 0;
                    p1_Id = p1.getStudents().get(i1).getId();
                    for(int j=0;j<p1.getStudents().size();j++){
                        if(j == i1){
                            p1.getStudents().get(j).setSelect(true);
                        }else {
                            p1.getStudents().get(j).setSelect(false);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    tv_note_title.setText(p1.getStudents().get(i1).getJob());
                    Map<String, String> map = new HashMap<>();
                    map.put("category_id", p1_Id + "");
                    map.put("title", ed_search.getText().toString());
                    post("note/noteList", map, NoteCategoryBean.class, false);
                }
//                } else if (i == 1) {
//                    Searchtype = 1;
//                    p2_Id = p2.getStudents().get(i1).getId();
//                    tv_note_title.setText("废纸篓");
////                    Map<String, String> map = new HashMap<>();
////                    map.put("category_id", p2_Id + "");
////                    map.put("title", ed_search.getText().toString());
////                    post("note/basketList", map, NoteCategoryBean.class, false);
//                }
                return false;
            }
        });
        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        //创建适配器
        noteadapter = new NoteAdapter(this.getActivity(), R.layout.item_note, lists);

        //给RecyclerView设置适配器
        recyclerView.setAdapter(noteadapter);
        noteadapter.bindToRecyclerView(recyclerView);
        noteadapter.setEmptyView(R.layout.empty_view);
        ((TextView)(noteadapter.getEmptyView().findViewById(R.id.tv_empty))).setText("你还没有笔记哦");
        noteadapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!lists.get(position).isWaste) {
                    Bundle bundle = new Bundle();
                    bundle.putString("category_name", tv_note_title.getText().toString());
                    bundle.putInt("category_id", p1_Id);
                    bundle.putInt("note_id", lists.get(position).note_id);
                    jumpTo(MyNoteActivity.class, 0, bundle);
                }
            }
        });
        noteadapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.bt_delete:
                        //删除垃圾篓笔记
                        new CommomDialog(getActivity(), R.style.dialog, "是否删除垃圾篓笔记!", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm) {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("note_id", lists.get(position).note_id);
                                    post("note/deleteNote", map, BaseBean.class, false);
                                    dialog.dismiss();
                                }
                            }
                        }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                        break;
                    case R.id.bt_reduction:
                        //还原笔记
                        new CommomDialog(getActivity(), R.style.dialog, "是否还原笔记!", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm) {
                                    Map<String, Object> rmap = new HashMap<>();
                                    rmap.put("note_id", lists.get(position).note_id);
                                    post("note/recoverNote", rmap, BaseBean.class, false);
                                    dialog.dismiss();
                                }
                            }
                        }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                        break;
                }
            }
        });
        ed_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if ((i == 0 || i == 3) && keyEvent != null) {
                    //点击搜索要做的操作
                    if (Searchtype == 0) {
                        Map<String, String> map = new HashMap<>();
                        map.put("category_id", p1_Id + "");
                        map.put("title", ed_search.getText().toString());
                        post("note/noteList", map, NoteCategoryBean.class, false);
                    } else {
                        Map<String, String> map = new HashMap<>();
                        map.put("category_id", p2_Id + "");
                        map.put("title", ed_search.getText().toString());
                        post("note/basketList", map, NoteCategoryBean.class, false);
                    }
                }
                return false;
            }
        });
        adapter.setMyonclick2(new ExtendListviewAdapter.Myonclick() {
            @Override
            public void onMyclick(View view, int i, int l) {
                if (i == 0) {
                    new InputDialog(getActivity(), R.style.dialog, new InputDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {

                        }

                        @Override
                        public void onClick(Dialog dialog, boolean confirm, EditText editText) {
                            if (confirm) {
                                Map<String, String> map = new HashMap<>();
                                map.put("name", editText.getText().toString());
                                post("note/addCategory", map, NoteCategoryBean.class, false);
                                dialog.dismiss();
                            }
                        }
                    }).setTitle("新建分类").settPositiveButtonColor(R.color.homepage_titlefont).show();
                } else {
                    new CommomDialog(getActivity(), R.style.dialog, "是否清空废纸篓", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            if (confirm) {
                                post("note/clearBasket", new HashMap(), NoteCategoryBean.class, false);
                                dialog.dismiss();
                            }
                        }
                    }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                }
            }
        });
        adapter.setMyonclick(new ExtendListviewAdapter.Myonclick() {
            @Override
            public void onMyclick(View view, final int i, final int l) {
                new CommomDialog(getActivity(), R.style.dialog, "是否删除该分类", new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            Map<String, String> map = new HashMap<>();
                            if (i == 0) {
                                map.put("category_id", p1.getStudents().get(l).getId() + "");
                            } else {
                                map.put("category_id", p2.getStudents().get(l).getId() + "");
                            }
                            post("note/delCategory", map, NoteCategoryBean.class, false);
                            dialog.dismiss();
                        }
                    }
                }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
            }

        });
    }

    @Override
    protected void formatData() {
        initData();
//        for (int i = 1; i <= 20; i++) {
//            NoteBean bean = new NoteBean();
//            bean.setTitle(i + "我是标题我是标题");
//            bean.setContent("我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内\n" +
//                    "我是内容我是内容");
//            bean.setTime("2018-8-30  19:23:01");
//            lists.add(bean);
//        }
        loadData();
    }

    private void loadData() {
        //获取分类列表
        Map<String, String> map = new HashMap<>();
        post("note/categoryList", map, NoteCategoryBean.class, false);
        //获取垃圾篓分类列表
        //Map<String, String> mapback = new HashMap<>();
        // post("note/basketList", map, NoteCategoryBean.class, false);
    }

    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_add:
                Bundle bundle = new Bundle();
                bundle.putString("typename",""+tv_note_title.getText().toString().trim());
                jumpTo(AddNewNoteActivity.class, 4,bundle);
                break;
        }
    }

    // 初始化数据
    public void initData() {
        p1.setName("我的笔记");
        p1.setSex(1);
        pList.add(p1);
        p2.setName("废纸篓");
        p2.setSex(2);
        pList.add(p2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //从 我的笔记 返回
        if (resultCode == 3) {
            if (data != null) {
                p1_Id = data.getIntExtra("category_id", 0);
            }
            Map<String, String> map = new HashMap<>();
            map.put("category_id", p1_Id + "");
            map.put("title", ed_search.getText().toString());
            post("note/noteList", map, NoteCategoryBean.class, false);
        }
        //从 添加笔记 返回
        else if (resultCode == 4) {
            if (data != null) {
                p1_Id = data.getIntExtra("category_id", 0);
            }
            Map<String, String> map = new HashMap<>();
            map.put("category_id", p1_Id + "");
            map.put("title", ed_search.getText().toString());
            post("note/noteList", map, NoteCategoryBean.class, false);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //获取分类列表
            Map<String, String> map = new HashMap<>();
            post("note/categoryList", map, NoteCategoryBean.class, false);
            //获取垃圾篓分类列表
            //Map<String, String> mapback = new HashMap<>();
            post("note/basketList", map, NoteCategoryBean.class, false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //获取分类列表
        Map<String, String> map = new HashMap<>();
        post("note/categoryList", map, NoteCategoryBean.class, false);
    }
}
